<template>
  <span @click="computeArea">测量面积</span>
</template>

<script setup>
import { ref, getCurrentInstance, onMounted } from "vue";
const { proxy } = getCurrentInstance();
import { usePopupStore } from "@/stores/popupStore";

const { showPopup } = usePopupStore();

import { drawGraph } from "@/zondyTools/ol-api/olDraw";
/* 构建放画笔的数据源 */
const source = new ol.source.Vector();
const layer = new ol.layer.Vector({
  source: source,
  id: "draw-area-layer",
  style: new ol.style.Style({
    fill: new ol.style.Fill({
      color: "rgba(0, 50, 200, 0.6)",
    }),
    stroke: new ol.style.Stroke({
      color: "rgba(0,50,200, 0.5)",
      width: 4,
    }),
  }),
});
let drawArea = null;
let $map = null;

/* 挂载时，将图层先添加到地图上，再实例化画笔 */
onMounted(() => {
  $map = proxy.$map;
  $map.addLayer(layer);
  //drawLine = drawGraph({ type: "Polygon", source });
});

/* 点击事件，触发画笔绘制 */
function computeArea() {
  drawArea = drawGraph({ type: "Polygon", source });
  $map.addInteraction(drawArea);

  drawArea.on("drawend", function (e) {
    $map.removeInteraction(drawArea);
    /* 获取绘制的线段坐标数据 */
    const feature = e.feature;
    const geometry = feature.getGeometry();
    const coordinates = geometry.getCoordinates();

    /* 利用turf库计算距离 */
    var polygon = turf.polygon(coordinates);
    const area = turf.area(polygon) / 1000000;
    //console.log(area);

    /* 计算线段中心，将长度以弹窗形式展示 */
    const center = turf.center(polygon);
    //console.log(center);

    showPopup({
      content: { 面积: area.toFixed(4) + "平方千米" },
      position: center.geometry.coordinates,
    });
  });
}
</script>

<style scoped></style>
